<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl着色器</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="400" height="490"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
  attribute vec4 a_Position;
void main(){
gl_Position =a_Position; //设置坐标
gl_PointSize =10.0; //设置尺寸
}
`
  //片元着色器伪代码
  var fShder_source = `
void main(){
gl_FragColor = vec4(0.5,0.0,0.0,1.0); //设置颜色
}
`
  function main() {
    var canvas = document.getElementById('canvas');
    //  获取上下文对象
    var gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      return;
    }
    // 获取attribute 变量的储存位置
    var a_Position = gl.getAttribLocation(gl.program, "a_Position");
    // 指定一个覆盖canvas的颜色
    gl.clearColor(1.0, 1.0, 1.0, 1.0);
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    canvas.onmousedown = function (event) {
      click(event, gl, canvas, a_Position);
    }
  }

  var g_point = [];
  function click(event, gl, canvas, a_Position) {
    var e = event || window.event;
    var x = e.clientX;//获取鼠标的点距离浏览器窗口最左边的距离
    var y = e.clientY;//获取鼠标的点距离浏览器窗口最上面的距离
    var rect = e.target.getBoundingClientRect();//组件封装方法，返回对象，里面含有点击的标签的距离浏览器左侧、上侧、右侧、下侧和自身的高宽

    // x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2);//计算出x轴WebGL的浮点数
    // y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2);//计算出y轴WebGL的浮点数

    x = ((x - rect.left) - canvas.width / 2) / (canvas.width / 2);
    y = (y - rect.top - canvas.height / 2) / (canvas.height / 2)*-1;


    g_point.push({ x: x, y: y });

    gl.clear(gl.COLOR_BUFFER_BIT);
    var len = g_point.length;
    for (var i = 0; i < len; i++) {
      gl.vertexAttrib3f(a_Position, g_point[i].x, g_point[i].y, 0.0);
      gl.drawArrays(gl.POINTS, 0, 1);
    }
  }
</script>

</html>